/**
 * Orienteering Sport Diary Copyright (C) 2009 OSDiary Team
 *
 * This file is part of Orienteering Sport Diary (OSDiary).
 *
 * OSDiary is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see http://www.gnu.org/licenses/.
 */

package org.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author George.Mavchun
 */
public class DateUtil {
    public static final String RFC_3339_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";
    public static final String DATE_AND_TIME_DISPLAY_FORMAT = "dd.MM.yyyy HH:mm";
    public static final String DATE_DISPLAY_FORMAT = "dd.MM.yyyy";
    public static final String HOURS_DISPLAY_FORMAT = "HH";
    public static final String MINUTES_DISPLAY_FORMAT = "mm";
    public static final String TIME_DISPLAY_FORMAT = HOURS_DISPLAY_FORMAT + ":" + MINUTES_DISPLAY_FORMAT;
    
    public static final SimpleDateFormat D_T_DISPLAY_FORMATTER = new SimpleDateFormat(DateUtil.DATE_AND_TIME_DISPLAY_FORMAT);
    public static final SimpleDateFormat DATE_DISPLAY_FORMATTER = new SimpleDateFormat(DateUtil.DATE_DISPLAY_FORMAT);
    public static final SimpleDateFormat HOURS_DISPLAY_FORMATTER = new SimpleDateFormat(DateUtil.HOURS_DISPLAY_FORMAT);
    public static final SimpleDateFormat MINUTES_DISPLAY_FORMATTER = new SimpleDateFormat(DateUtil.MINUTES_DISPLAY_FORMAT);
    public static final SimpleDateFormat TIME_DISPLAY_FORMATTER = new SimpleDateFormat(DateUtil.MINUTES_DISPLAY_FORMAT);

    public static long parseRFC(String source) {
        int idx = source.lastIndexOf(":");
        String result = source.substring(0, idx);
        result += source.substring(idx + 1);
        return parse(result, RFC_3339_FORMAT);
    }

    public static long parse(String source, String dateFormat) {
        Date temp = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat(dateFormat);
            temp = format.parse(source);
        } catch (ParseException ex) {
            Logger.getLogger(DateUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (null == temp) {
            return -1;
        } else {
            return temp.getTime();
        }
    }

    public static String format(long millis, String dateFormat) {
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        return format.format(new Date(millis));
    }
}
